//
// Created by ta&to on 2022/8/16.
//
#include "http_connect.h"
void http_init(thread_pool_t *tpt, log_t *logt, http_socket_event_t *hset, void* func) {
    hset->hgdc = (struct http_global_data_container *) http_malloc(sizeof(struct http_global_data_container));
    hset->hgdc->tpt = tpt;
    getcwd(hset->workpath, PATH_MAX);
    initLeader(&hset->hgdc->req_maps_header);
    init_lock(&hset->hgdc->req_maps_header_lock);
    initLeader(&hset->hgdc->req_maps_fds);
    init_lock(&hset->hgdc->req_maps_fds_lock);
    initLeader(&hset->hgdefc->func_handler);
    init_lock(&hset->hgdefc->event_fun_lock);
#ifdef HTTPSERVER_OPEN
    // 处理http
    http_handler_t hht;
    http_event_context_control_t hecct;
    hht.func = func;
    hecct.func_handler = &hht;
#endif
    http_start_io(logt, hset);
}
void conn_init(thread_pool_t *tpt, log_t *logt, http_socket_event_t *hset, int listen_port, int outtime_sec, void* __socket_r_func, void* __socket_w_func){
    // 处理IO
    http_socket_event_handle_t *handler = (struct http_socket_event_handle_s *) http_malloc(sizeof(struct http_socket_event_handle_s));
    hset->hgdefc = (struct http_global_data_event_func_container *) http_malloc(sizeof(struct http_global_data_event_func_container));
    hset->logs = logt;
    hset->max_link = MAXCLINE;
    hset->socket_fd = CreateHttpSocket(logt, 0, listen_port, 128);
    hset->maxfd = hset->socket_fd;
    hset->workpath = (char *) http_calloc(PATH_MAX * sizeof(char));
    handler->data_len = BUF_SIZE;
    handler->func_read = __socket_r_func;
    handler->func_write = __socket_w_func;
    hset->hgdefc->temp_func_handler = handler;
    if(outtime_sec == -1)
        hset->tvp = NULL;
    else {
        struct timeval tvp;
        tvp.tv_sec = outtime_sec;
        tvp.tv_usec = 0;
        hset->tvp = &tvp;
    }
}

// 获取一个已完成三次握手的连接
int conn_handler(log_t *logt, struct http_socket_event_loop_s *hset, http_socket_event_handle_t *handler)
{
    int client_fd = Accept(logt, hset->socket_fd, (struct sockaddr *)&handler->client_addr,&handler->sin_size);
    if(!client_fd)
        error(logt, "one client link fail[%d]", client_fd);
    else
        debug(logt, "one client link success[%d]", client_fd);
    return client_fd;
}
